package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"goods_svc/goods"
	"goods_svc/internal/svc"
	"goods_svc/models/cache"
	"goods_svc/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderListLogic {
	return &OrderListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 订单列表
func (l *OrderListLogic) OrderList(in *goods.OrderListRequest) (*goods.OrderListResponse, error) {
	// todo: add your logic here and delete this line

	var orders []mysql.Order
	mysql.DB.Debug().Find(&orders)

	//使用缓存
	key := fmt.Sprintf("order_list_")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result != "" {
		fmt.Println("使用缓存")
		json.Unmarshal([]byte(result), &orders)
	} else {
		marshal, _ := json.Marshal(orders)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*5)
	}

	//去mysql数据库查询一下
	var OrderList []*goods.OrderList
	for _, order := range orders {
		list := goods.OrderList{
			UserId: int64(order.UserId),
			ShopId: int64(order.ShopId),
			Name:   order.Name,
			Price:  float32(order.Price),
			Num:    int64(order.Num),
		}
		OrderList = append(OrderList, &list)
	}

	//实现展示
	return &goods.OrderListResponse{
		List: OrderList,
	}, nil
}
